package com.source.juccthread;

import java.util.concurrent.TimeUnit;

/**
 * @Author wengqy
 * @Date 2021/1/20
 */
public class Wait007 {
    public static void main(String[] args) {

    Resource resource  = new Resource();
    Product product = new Product(resource);
    Consumer consumer = new Consumer(resource);

        Thread pro = new Thread(product);
        pro.setName("Product: ");
        Thread con = new Thread(consumer);
        con.setName("Consumer: ");


        pro.start();
        con.start();

    }


    public static  class  Resource{
       int  num  = 0;

       public synchronized void  add(){

           if(num >=5){
               try {
                   wait();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }else{
               num  = num + 1;
               System.out.println(Thread.currentThread().getName() + ":" + "添加了第" + num + "个产品");
               notifyAll();// 产品数量没到上线，通知其他线程来进行存或则取
           }
       }


        public synchronized void getProduct() {
            if (num <= 0) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + ":" + "买走了第" + num + "个产品");
                num = num - 1;

                notifyAll();// 产品数量没到下线，通知其他线程来进行存或则取
            }
        }
    }




    public   static  class  Product implements Runnable {
       private Resource resource;

        public Product(Resource resource) {
            this.resource = resource;
        }

        @Override
        public void run() {

            while(true){
                try {
                    TimeUnit.MILLISECONDS.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                resource.add();
            }
        }
    }



    public   static  class  Consumer implements Runnable {
        private Resource resource;

        public Consumer(Resource resource) {
            this.resource = resource;
        }

        @Override
        public void run() {

            while(true){
                try {
                    TimeUnit.MILLISECONDS.sleep(300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                resource.getProduct();
            }
        }
    }




}
